﻿

// 从start处开始截取input数组
app.filter('offset', function() { 
	return function(input, start) {
		start = parseInt(start,10);
		return input.slice(start) 
		}
})


// 生成dom元素时，自动获得焦点
app.directive('autoFocus', function($timeout) {
    return {
        restrict: 'A',
        link: function(_scope, _element) {
            $timeout(function(){
                _element[0].focus();
            }, 10);
        }
    };
});

/*---------------------textInput--------------------
文字显示，点击编辑

@parem:
	model:
	[self]:
	[onchanged]:
	[pattern]:string:正则表达式
@method:
	self.show()
example:
	<span text-input
		self='record.start_time_editor'
		model='record.start_time' 
		onchanged='record.start_time_dirty=true;record.dirty=true' 
		width='130px' 
		pattern='^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$' >
	</span>
*
*/
app.directive('textInput',function () {
	// <span db-text model='record.end_time' dirty='record.end_time_dirty' width='80px' pattern='^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}$'></span>
	return {
		restrict:'AE',
		scope:{
			model:'=',
			self:'='
		},
		template:"<span'>\
		          <span ng-bind='model' ng-show='!showEditor' ng-click='self.show()'></span>\
		          <span ng-if='showEditor'>\
			      <input auto-focus ng-class='is_valid' style='[[style]];outline:0 none'  type='text' name='ggg' ng-model='$parent.inputModel' ng-blur='onblur()'/>\
			       </span>\
	              </span>",
	    link:function (scope,ele,attr) {
		    function __init__(self) {
		    	self.show=function () {
				    scope.showEditor=true;
			    }
		    }
		    scope.onblur=function () {
		    	scope.showEditor=false;
		    	scope.inputModel=scope.model;
		    }
		    
		    scope.onchanged=function () {
		    	if(attr.onchanged){
			    	scope.$parent.$eval(attr.onchanged)
		    	}
		    }
		    function _valid_changed(newval) {
		    	if(scope.model!=newval){
					  scope.onchanged();
				    }
		    	scope.model=newval;
		    	scope.is_valid=''
		    }
		    
		    //-----
		    
			if(typeof scope.self=='undefined'){
				    scope.self={}
		    }
		    __init__(scope.self);
		    scope.$watch('self',function (newval,oldval) {
		    	if(typeof scope.self=='undefined'){
				    scope.self={}
				   	__init__(scope.self)
		    	}
		    })
		    
		    if(attr.width){
			    scope.style='width:'+attr.width;
		    }else{
			    scope.style=''
		    }
		    
		    scope.inputModel=scope.model;
	    	scope.$watch('inputModel',function (newval,oleval) {
		    	if(attr.pattern){
			    	var pt =new RegExp(attr.pattern);
			    	if(pt.test(newval)){
				    	_valid_changed(newval)
			    	}else{
				    	scope.is_valid='input-invalid'
			    	}
		    	}else{
			    	_valid_changed(newval)
		    	}
	    	})
	    }
	}
})


// 按照order数组里面的循序，排列inputArray:[{name:'one'},{name:'two'}]的顺序
app.filter('orderList',function(){
    return function(inputArray,order){
        var array = [];
        for (x in order){
	        for(y in inputArray){
		        if (inputArray[y].name==order[x]){
			        array.push(inputArray[y])
		        }
	        }
        }
        return array;
    }
});


/* -----------------------textSelect----------------------
文字显示，点击选择

@param
	model: 
	options:Array: 选项，如：['A','B','C']
	[self]:obj or undefined : 元素在parentScope中的标识
	[onchanged]:express:
@method
	self.show():触发显示选择框

example:
<span text-select
	class="status_span" 
	ng-class='check.status'  
	model='check.status' 
	self='dog'
	options='["approved","rejected","pending"]' 
	onchanged='record.check_record_dirty;record.dirty=true'>
	Approved
</span>
*/
app.directive('textSelect',function () {
	return {
		restrict:'A',
		scope:{
			model:'=',
			self:'=',
			options:'=',
		},
		template:"<span style='position: relative;' ng-click='self.show();$event.stopPropagation()'>\
				   <span ng-bind='label_it(model)'></span>\
			        <ul ng-if='showEditor' class='pop_option'>\
				     <li ng-bind='option' ng-repeat='option in options' ng-click='liclick(option,$event)'></li>\
			         </ul>\
			      </span>",
			      
	    link:function (scope, ele, attr) {
		    function __init__(self) {
		    	self.show=function () {
			    	scope.showEditor=true;
		    	}
		    }

		    scope.onchanged=function () {
		    	if(typeof attr.onchanged){
			    scope.$parent.$eval(attr.onchanged)
		    	}
		    }
		    
		    if(typeof scope.self=='undefined'){
			    scope.self={}
		    }
		    __init__(scope.self)
		    scope.$watch('self',function (newval,oldval) {
		    	if(typeof scope.self=='undefined'){
			    	scope.self={}
			    	__init__(scope.self)
		    	}
		    })
		    scope.showEditor=false
			$( "body" ).click(function() {
				if(scope.showEditor){
					scope.$apply(function () {
					scope.showEditor=false;
				})}
			});
	    },
	    controller:function ($scope) {
		    $scope.label_it=function (model) {
		    	for(x in $scope.choices){
			    	if($scope.choices[x].value==model){
				    	return $scope.choices[x].name
			    	}
		    	}
		    	return model
		    }
	    	$scope.liclick=function (option,event) {
		    	if(option!=$scope.model){
			    	$scope.onchanged()
		    	}
	    		$scope.model=option;
				$scope.showEditor=false;
		    	event.stopPropagation()
		    	
	    	}
	    }
	              
	} 
})


/*

*/
app.directive('sortMark',function () {
	//<span sort-mark name='field.name' items='records'></span>
	return {
		restrict :'A',
		replace:true,
		transclude:true,
		scope:{
			items:'=',
			name:'=',
			//rt:'='
		},
		template:"<span ng-click='sort()' class='sort-head'>\
				<span ng-class='{\"low\":!is_sort}' ng-show='positive||!is_sort' class='fa fa-caret-up'></span>\
				<span ng-class='{\"low\":!is_sort}' ng-show='!positive||!is_sort' class='fa fa-caret-down'></span><span ng-transclude></span></span>",
		controller:function ($scope) {
			if(typeof $scope.items =='undefined'){
				$scope.items=[];
			}
			//$scope.is_sort=function () {
			//	if(typeof $scope.items.crt_name!='undefined'){
			//		return $scope.items.crt_name==$scope.name
			//	}else{
			//		return false;
			//	}
			//};
			$scope.$on('otherSortClick',function (event,name) {
				if(name==$scope.name){
					$scope.is_sort=true
				}else{
					$scope.is_sort=false
				}
			})
			$scope.sort=function () {
				// 排序表格
				//$scope.items.crt_name=$scope.name
				if($scope.positive){
					$scope.positive=false;
				}else{
					$scope.positive=true;
				}
				$scope.$emit('sortClick',$scope.name)
				//$scope.items=$filter('orderBy')($scope.items, prefix+$scope.name)
				$scope.items.sort(function (a,b) {
					var rt;
					if (a[$scope.name]>b[$scope.name]){
							rt= 1
						}else if(a[$scope.name]<b[$scope.name]){
							rt= -1
						}else{
							rt= 0
						}
						
					if ($scope.positive){
						return rt
					}else{
						return -rt
					}
				})
		   }
		}
		
	}
})

// 页面的角标，输入参数：per:每页数量,crt：当前页编号，items:数组
// 之所以传入items，而不适items.length，是因为items.length可能会发生变化
app.directive('pageFoot',function () {
	return {
		restrict :'A',
		scope:{
			itemsPerPage:'=per',
			currentPage:'=crt',
			items:'='
		},
		template:"<ul class='pagination'>\
				<li ng-class='prevPageDisabled()'>\
					<a href ng-click='prevPage()'>Prev</a>\
				</li>\
				<li ng-repeat='n in range()' ng-class='{active: n == currentPage}' ng-click='setPage(n)'>\
					<a href='' ng-bind='n+1'></a> </li>\
				<li ng-class='nextPageDisabled()'>\
					<a href ng-click='nextPage()'>Next</a>\
				</li> \
			</ul>",
	
	link:function (scope, ele, attr) {
		//if (angular.isUndefined(scope.allowSomething))
  //      $scope.allowSomething = true;
  
   // 		scope.itemsPerPage = 57;
			//scope.currentPage = 0;
			//scope.items = items
  			scope.prevPage = function() { 
			if (scope.currentPage > 0) {scope.currentPage-- }
			};


			scope.prevPageDisabled = function() {
				return scope.currentPage === 0 ? "disabled" : "";
			};

			scope.pageCount = function() {
				return Math.ceil(scope.items.length/scope.itemsPerPage)-1;
			};
			scope.range=function () {
				var out=[];
				var length=scope.pageCount();
				for(var x =0;x<=length;x++){
					out.push(x)
				}
				return out
			}
			scope.setPage=function (n) {
				scope.currentPage=n;
			}
			scope.nextPage = function() {
			if (scope.currentPage < scope.pageCount()) {
				scope.currentPage++;
				}
			};

			scope.nextPageDisabled = function() {
				return scope.currentPage === scope.pageCount() ? "disabled" : "";
			}
	}
}
})


app.directive('getExcel',function ($http) {
	// <span get-excel data='reports' heads='heads' url='/attendance/getexcel/' class="fa fa-sort-amount-desc toolbtn"></span>
	// heads: 表格的头
	// data: 表格的Array
	return {
		restrict :'A',
		replace:true,
		scope:{
			data:'=',
			heads:'='
		},
		template:"<span ng-click='get_excel_from_server()'></span>",
		link:function (scope,ele,attr) {
			scope.url=attr.url
			scope.get_excel_from_server=function (data,url) {
				post(scope.url,{data:scope.data,heads:scope.heads})
			
			}
			
			
		}
	}
})
//----------------------------------------------------------------------
/* ------------------fileLoader----------------------
文件加载
[self]
*/
app.directive('fileLoader',function ($http) {
	return {
		restrict :'A',
		replace:true,
		scope:{
			self:'='
		},
		template:"<input model='filebody' type='file'>",
		link:function (scope,ele,attr) {
			scope.self={	name:'',
							uploading:false};
			ele.bind("change", function (changeEvent) {
                var fd = new FormData();
                file=changeEvent.target.files[0]
   				fd.append('file', file);
   				scope.$apply(function () {
   					scope.filebody=fd;
   					scope.self.name=file.name;
   					if(attr.onload){
	   					scope.$parent.$eval(attr.onload)
   					}
   				})
            });
            scope.self.upload=function (url) {
	            scope.self.uploading=true;
	    		rt= $http.post(url,scope.filebody,{
		                  transformRequest: angular.identity,
		                  headers: {'Content-Type': undefined}
	            })
	            rt.success(function () {
	            	scope.self.uploading=false;
	            })
	            return rt
    		}
		},
	}
});

/*
用于过滤数据
@param
items: array : [{empid:"AE1856",type:"annual_leave"},...]
name:string: items中被过滤列的名字
[self] :object : 在parentScope中的标识对象
[onchanged]:express: 过滤器选择变化时，触发

@self.method:
self.show():显示选择框
self.update_options()

example:
<span head-filter 
	items='org_records' 
	name='[[head.name]]' 
	self='head._filter'
	onchanged='filter_records()'>
    <span class="glyphicon glyphicon-filter" 
    	aria-hidden="true">
    </span>
</span>
*/
app.directive('headFilter',function () {
	return {
		restrict:'A',
		transclude:true,
		scope:{
			self:'=',
			items:'=',
		},
		template:"<span style='position: relative;' \
					ng-click='self.show();$event.stopPropagation()'>\
						<span ng-transclude></span>\
			        	<ul ng-if='showEditor' \
			        		class='pop_option' \
			        		style='width:150px;max-height:300px;overflow:auto;'>\
					     	<li ng-repeat='it in sel_list' \
					     		ng-click='liclick(it,$event)'>\
					     		<input type='checkbox' \
					     			ng-model='it.value'/>\
					     		<span ng-bind='it.name' \
					     			ng-click='it.value=!it.value'>\
					     		</span>\
					     	</li>\
			         	</ul>\
			      </span>",
			      //ng-click='liclick(choice,$event)
	    link:function (scope, ele, attr) {
		    function __init__(self) {
			    self.show=function () {
			    	scope.showEditor=true;
			    }
			    self.update_options=function () {
			    	scope.sel_list=_init_sel_list(scope.items)
			    }
			    self.update_options()
		    }
		    
		    if(typeof scope.self=='undefined'){
			    scope.self={};
		    }
			__init__(scope.self)
		    scope.name=attr.name;
		    
			$( "body" ).click(function() {
				if(scope.showEditor){
					scope.$apply(function () {
						scope.showEditor=false;
					})
				}
			});
			scope.$on('arrayUpdated',function (e,array) {
				if(array==scope.items){
					scope.self.update_options()
				}
			})
			scope.onchanged=function () {
				if(attr.onchanged){
					scope.$parent.$eval(attr.onchanged)
				}
				scope.$emit('head_filter_changed',scope.self)
			}
			function _init_sel_list(items) {
			    var inn_list=[];
		    	for(x in items){
			    	if(inn_list.indexOf(items[x][scope.name])==-1){
				    	inn_list.push(items[x][scope.name])
			    	}
		    	}
		    	var list_with_val=[{name:'(select all)',value:true}];
		    	for (x in inn_list){
			    	list_with_val.push({name:inn_list[x],value:true})
		    	}
		    	return list_with_val
		    };
		    //scope.sel_list=scope.init_sel_list(scope.items)
		    scope.$watch('items',function (n,o) {
		    	scope.sel_list=_init_sel_list(n)
		    });

		    scope.self.filter=function (inputArray) {
		    	var array=[];
		    	for (x in inputArray){
			    	for (y in scope.sel_list){
				    	if (scope.sel_list[y].name==inputArray[x][scope.name] && scope.sel_list[y].value){
					    	array.push(inputArray[x])
				    	}
			    	}
		    	}
		    	return array
		    }
	    },

	    controller:function ($scope) {
	    	$scope.liclick=function (it,event) {
		    	//it.value=!it.value
		    	if(it.name=='(select all)'){
			    	for(x in $scope.sel_list){
				    	$scope.sel_list[x].value=it.value;
			    	}
		    	}
		    	$scope.onchanged();
		    	//$scope.$emit('headFilter',$scope.self.filter)
		    	event.stopPropagation()
	    	}
	    }      
	} 
})